//
//  ViewController.m
//  DynamicPlayground
//
//  Created by steven.zhan on 14-8-28.
//  Copyright (c) 2014年 hpxbzz. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    UIDynamicAnimator *_animator;
    UIGravityBehavior *_gravity;
    UICollisionBehavior *_collision;
    BOOL _firstContact;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    UIView *square=[[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    square.backgroundColor=[UIColor grayColor];
    [self.view addSubview:square];
    
    
    UIView *barrier=[[UIView alloc] initWithFrame:CGRectMake(0, 300, 130, 20)];
    barrier.backgroundColor=[UIColor redColor];
    [self.view addSubview:barrier];
    
    _animator=[[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    _gravity=[[UIGravityBehavior alloc] initWithItems:@[square]];
    [_animator addBehavior:_gravity];
    
    _collision=[[UICollisionBehavior alloc] initWithItems:@[square]];
    _collision.translatesReferenceBoundsIntoBoundary=YES;
    _collision.collisionDelegate=self;
    //_collision.action=^{
    //NSLog(@"%@,%@",NSStringFromCGAffineTransform(square.transform),NSStringFromCGPoint(square.center));
    //};
    [_animator addBehavior:_collision];
    
    CGPoint rightEdge=CGPointMake(barrier.frame.origin.x+barrier.frame.size.width, barrier.frame.origin.y);
    [_collision addBoundaryWithIdentifier:@"barrier" fromPoint:barrier.frame.origin toPoint:rightEdge];
    
    UIDynamicItemBehavior *itemBehaviour=[[UIDynamicItemBehavior alloc] initWithItems:@[square]];
    itemBehaviour.elasticity=0.8;
    //itemBehaviour.density=0;
    //itemBehaviour.allowsRotation=NO;
    [_animator addBehavior:itemBehaviour];
    
    

}


- (void)collisionBehavior:(UICollisionBehavior*)behavior    beganContactForItem:(id <UIDynamicItem>)item withBoundaryIdentifier:(id <NSCopying>)identifier atPoint:(CGPoint)p
{
    NSLog(@"Boundary contact occrred-%@",identifier);
    
    
    UIView *veiw=(UIView*)item;
    veiw.backgroundColor=[UIColor yellowColor];
    [UIView animateWithDuration:0.3
                     animations:^{
                         veiw.backgroundColor=[UIColor grayColor];
                     }];
    
    if (!_firstContact) {
        
        _firstContact = YES;
        
        UIView  *square=[[UIView alloc] initWithFrame:CGRectMake(30, 0, 100, 100)];
        square.backgroundColor=[UIColor grayColor];
        [self.view addSubview:square];
        [_collision addItem:square];
        [_gravity addItem:square];
        
        UIAttachmentBehavior *attach=[[UIAttachmentBehavior alloc] initWithItem:veiw attachedToItem:square];
        [_animator addBehavior:attach];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
